package com.example.sunmiv1.dialog;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.VipInfoAdapter;
import com.example.sunmiv1.entity.VipListBean;
import com.example.sunmiv1.scan.InfraredScanActivity;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

public class VipLoginDialog extends BaseDialog {


    @BindView(R.id.dialog_vipLogin_close)
    ImageView dialogVipLoginClose;
    @BindView(R.id.dialog_vipLogin_edit)
    EditText dialogVipLoginEdit;
    @BindView(R.id.dialog_vipLogin_scavenging)
    ImageView dialogVipLoginScavenging;
    @BindView(R.id.dialog_vipLogin_sure)
    TextView dialogVipLoginSure;
    Unbinder unbinder;
    @BindView(R.id.lv_vip_info)
    ListView lvVipInfo;
    Unbinder unbinder1;

    private LoadingDialog loadingDialog;


    //尾號查詢到的會員集合
    private List<VipListBean.InfoBean> vipInfoList = new ArrayList<>();
    //尾號集合Adapter
    private VipInfoAdapter vipInfoAdapter;
    private VipListBean vipListBean;

    private VipListBean.InfoBean infoBean;

    private ACache aCache;

    public static VipLoginDialog newInstance() {
        VipLoginDialog fragment = new VipLoginDialog();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_vip_login;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            // 下面這些設置必須在此方法(onStart())中才有效
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0xff000000));
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            Window window = dialog.getWindow();
            // 如果不設置這句代碼, 那麼彈框就會與四邊都有一定的距離
            window.setBackgroundDrawableResource(android.R.color.transparent);
            window.setWindowAnimations(R.style.DialogFromBottom);// 設置動畫
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = dp2px(300);
            params.gravity = Gravity.CENTER;
            window.setAttributes(setLayout(params));
        }
    }

    @Override
    protected void initData() {
        aCache = ACache.get(getContext());
        loadingDialog = new LoadingDialog(getContext());
    }


    @OnClick({R.id.dialog_vipLogin_close, R.id.dialog_vipLogin_scavenging, R.id.dialog_vipLogin_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dialog_vipLogin_close:
                dismiss();
                break;
            case R.id.dialog_vipLogin_scavenging:
                startQrCode();
                break;
            case R.id.dialog_vipLogin_sure:
                if ("".equals(dialogVipLoginEdit.getText().toString().trim())) {
                    Toast.makeText(getContext(), "請先輸入會員賬號", Toast.LENGTH_SHORT).show();
                    return;
                }
                GetVipInfo();
                break;
        }
    }

    /*獲取會員信息*/
    private void GetVipInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("vipCode", dialogVipLoginEdit.getText().toString().trim());//card_num
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(getContext(), Common.GET_VIP_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Message msg = new Message();
                        if (json.has("msg")) {
                            Toast.makeText(getContext(), json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                        if (json.getInt("status") == 1 || json.getInt("status") == 2) {
                            vipListBean = GsonUtils.JsonToBean(text, VipListBean.class);
                            aCache.put("density_free", vipListBean.getDensity_free_state());
                            vipInfoList.clear();
                            vipInfoAdapter = new VipInfoAdapter(getContext(), vipInfoList);
                            lvVipInfo.setAdapter(vipInfoAdapter);
                            for (int i = 0; i < vipListBean.getInfo().size(); i++) {
                                vipInfoList.add(vipListBean.getInfo().get(i));
                            }
                            if (vipInfoList.size() == 1) {
                                infoBean = vipInfoList.get(0);
                                callback.success(infoBean);
                                dismiss();
                            } else {
                                lvVipInfo.setVisibility(View.VISIBLE);
                                vipInfoAdapter = new VipInfoAdapter(getContext(), vipInfoList);
                                lvVipInfo.setAdapter(vipInfoAdapter);
                            }
                            lvVipInfo.setOnItemClickListener((adapterView, view, i, l) -> {
                                infoBean = vipInfoList.get(i);
                                callback.success(infoBean);
                                dismiss();
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        //Intent intent = new Intent(getContext(), CaptureActivity.class);
        Intent intent = new Intent(getContext(), InfraredScanActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(getContext(), "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            dialogVipLoginEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            GetVipInfo();
        }
    }

}
